package com.x2.base.jdbc;

import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
public class TableMeta {

    private List<FieldMeta> fieldList;

    private String tableName;

    public TableMeta(List<FieldMeta> fieldList, String tableName) {
        this.fieldList = fieldList;
        this.tableName = tableName;
    }

    private static Map<Class, TableMeta> cacheInfo = new HashMap<>();


    /**
     * 初始化
     *
     * @param clasz
     * @return
     */
    public synchronized static TableMeta get(Class clasz) {
        if (cacheInfo.containsKey(clasz)) {
            return cacheInfo.get(clasz);
        }
        Field[] fields = clasz.getDeclaredFields();
        List<FieldMeta> fieldVOS = new ArrayList<>();
        TableField tempField;
        TableId tempIdField;
        for (Field f : fields) {
            tempField = f.getAnnotation(TableField.class);
            if (tempField != null) {
                if(tempField.value() == null){
                    continue;
                }
                fieldVOS.add(new FieldMeta(tempField.value(), f.getName(), null));
            } else {
                tempIdField = f.getAnnotation(TableId.class);
                if (tempIdField != null) {
                    if(tempIdField.value() == null){
                        continue;
                    }
                    fieldVOS.add(new FieldMeta(tempIdField.value(), f.getName(), tempIdField.type().toString()));
                }
            }
        }
        TableName tableName = (TableName) clasz.getAnnotation(TableName.class);
        TableMeta jw = new TableMeta(fieldVOS, tableName.value());
        cacheInfo.put(clasz, jw);
        return jw;
    }

}
